﻿using HpxWMS_Api.BLL;
using HpxWMS_Api.Models;
using HpxWMS_Api.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace HpxWMS_Api.Controllers
{
    /// <summary>
    /// 账户接口
    /// </summary>
    public class AccountController : ApiController
    {

        /// <summary>
        /// 应用业务逻辑层接口
        /// </summary>
        public AccountManager accountmanager = new AccountManager();

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <returns></returns>
        [Route("api/Account/Login")]
        public R<UserVO> Login([FromBody]Li li)
        {
            //数据校验
            if (!ModelState.IsValid)
            {
                //标准返回HTTP状态码400
                //[200~300) 成功
                //[300,400) 重定向
                //400 错误请求
                //401 未授权
                //403 禁止访问
                //404 访问呢的资源不存在
                //500 服务器错误
                throw new ClientException(HttpStatusCode.BadRequest);
            }
            //逻辑代码
            var user = accountmanager.Login(li);
            if (user != null)
            {
                //准备生成token的数据
                AuthInfo authInfo = new AuthInfo();
                authInfo.Id = user.Id;
                authInfo.Name = user.NickName;
                authInfo.CreateTime = DateTime.Now;
                authInfo.ExpiredTime = DateTime.Now.AddMinutes(5);
                //生成token
                var token = JwtHelper<AuthInfo>.MackJwt(authInfo);
                return new R<UserVO>()
                {
                    Code = "000",
                    Message = "登录成功",
                    Data = new UserVO
                    {
                        NickName = user.NickName,
                        Token = "Bearer " + token
                    }
                };
            }

            return new R<UserVO>() { Code = "999", Message = "登录失败" };
        }
    }
}
